'use strict';

import React from 'react';
import { connect } from 'react-redux';
import { Link} from 'react-router';
import * as actions from '../../actions/ring_zhekou_edit_items';
import * as set_item_actions from '../../actions/ring_tags_step3';
import { Button,Icon,Dialog,Pagination,Input,Loading,Menu,NumberPicker } from 'qnui';
import Radio,{ Group as RadioGroup } from 'qnui/lib/radio';
import { Row, Col } from 'qnui/lib/grid';
import Breadcrumb from 'qnui/lib/breadcrumb'
import Step, { Item as StepItem } from 'qnui/lib/step';
import './index.scss';

class RingZhekouEditItems extends React.Component {
    constructor(props) {
        super(props);
		this.dispatch = this.props.dispatch;
        this.state = {
			refreshDialog:false,
			refreshContent:"",
			currentPage:1,
			pageSize:10,
			activity_id:this.props.location.query.activity_id?this.props.location.query.activity_id:0,
			act_type:this.props.location.query.act_type
        };
    }
	componentWillMount(){
		this.setState({activity_id:this.props.location.query.activity_id});
		this.dispatch(
			actions.getList({
				act_type:this.state.act_type,
				activity_id:this.props.location.query.activity_id,
				page:1,
				page_size:this.state.pageSize
			})
		);
	}
	onClose(){
		this.dispatch(actions.closeDialog());
		this.dispatch(set_item_actions.closeDialog());
	}
	handleCheckStatus(){
		return;
	}
	handlePageChange(page){
		this.setState({"currentPage":page});
		this.dispatch(
			actions.getList({
				act_type:this.state.act_type,
				activity_id:this.state.activity_id,
				page:page,
				page_size:this.state.pageSize
			})
		);
	}
	handlePageSizeChange(size){
		this.setState({"currentPage":1,"pageSize":size});
		this.dispatch(
			actions.getList({
				act_type:this.state.act_type,
				activity_id:this.state.activity_id,
				page:1,
				page_size:size
			})
		);
	}
	changePrice(ztype,item,value){
		this.dispatch(
			actions.resetItem(ztype,item,value)
		);
	}
	changeLimitPrice(ztype,item,value){
		this.dispatch(
			actions.resetLimitItem(ztype,item,value)
		);
	}
	changeLimit(item,value){
		this.dispatch(
			actions.resetLimit(item,value)
		);
	}
	editItemInActive(num_iid){
		if(this.loginRefresh()){
			return;
		}
		const doneItems = this.props.ring_zhekou_edit_items.data.items.item;
		doneItems.map(item=>{
			if(item.num_iid==num_iid){
				this.dispatch(
					set_item_actions.editItemInActive(item,this.state.act_type)
				);
				return;
			}
		});
	}
	removeItemInActive(detail_id){
		if(this.loginRefresh()){
			return;
		}
		this.dispatch(
			actions.removeItem(this.state.activity_id,detail_id,this.state.act_type)
		);
	}
	
	loginRefresh(){
		
		const ts = Date.parse(new Date())/1000;
		if(parseInt(window.info.timestemp)+1700 < ts){
			// 操作授权超过半小时，请重新授权
			let _self = this;
			// window.parent.closeRefreshDialog();  iframe页面调用该关闭方式
			window.closeRefreshDialog = (info)=>{
				window.info = info; //刷新已授权的信息
				_self.setState({"refreshDialog":false});
			}
			this.setState({"refreshDialog":true,"refreshContent":{"title":"敏感操作授权超时","msg":"请授权并在30分钟以内完成创建折扣。","content":<iframe name="showLogin" id="showLogin" style={{border:"none",height:"360px",width:"100%"}}  scrolling="no" src={"https://oauth.taobao.com/authorize?client_id=21127968&redirect_uri=http%3A%2F%2Fllxl.hz.taeapp.com%2F?a=refresh&response_type=code&state=llxl.hz.taeapp.com.21127968&view=web&ts="+ts} />}});
			return true;
		}
		return false
	}
	onRefreshClose(){
		this.setState({"refreshDialog":false});
	}
  render() {
	const hasError = ( this.props.ring_zhekou_edit_items.error || this.props.ring_tags_step3.error);
	const isLoading = (this.props.ring_zhekou_edit_items.loading || this.props.ring_tags_step3.loading);
	const loginBtn = this.props.ring_zhekou_edit_items.loginError?
				<a href="https://oauth.taobao.com/authorize?response_type=code&client_id=21127968&redirect_uri=http://llxl.hz.taeapp.com/?state=ring_zhekou_edit_items&view=web"><Button size="large" type="primary"><span>请重新登陆</span></Button></a>
			 :"";
	const footer = this.props.ring_zhekou_edit_items.loginError?<div>{loginBtn}</div>:"";
	const creatingTitle = isLoading?"正在读取。。。":"错误信息";
	const creatingMsg = isLoading?<Loading />:(this.props.ring_zhekou_edit_items.message+this.props.ring_tags_step3.message);
	const data = this.props.ring_zhekou_edit_items.data;
	const doneItems = data?data.items.item:[];
	const total = data?parseInt(data.total_count):0;
	const noneMsg = total?"":isLoading?<Row justify="center">正在读取。。。</Row>:<Row justify="center">活动中没有任何商品</Row>;
	return (
        <div className="page1-page">
			<Dialog
					visible = {this.state.refreshDialog}
                    onOk = {this.onRefreshClose.bind(this)}
                    onCancel = {this.onRefreshClose.bind(this)}
                    onClose = {this.onRefreshClose.bind(this)} 
					title = {this.state.refreshContent.title}
					style={{width:"445px",height:"360px"}}
					footer = {false}
					>
					<Row justify="center">
						{this.state.refreshContent.msg}
					</Row>
					<Row justify="center">
						{this.state.refreshContent.content}
					</Row>
            </Dialog>
			<Row style={{background:"#F6F6F6",margin:"3px 0",height:"43px"}} justify="start">
			<Col span="8" align="center">
			<Breadcrumb maxNode={5}>
				  <Breadcrumb.Item>打折活动</Breadcrumb.Item>
				  <Breadcrumb.Item>限时折扣</Breadcrumb.Item>
				  <Breadcrumb.Item>活动列表</Breadcrumb.Item>
			  </Breadcrumb>
			</Col>
		  </Row>
			<Dialog style={{width:"300px"}} 
					visible = {hasError || isLoading}
                    onOk = {this.onClose.bind(this)}
                    onCancel = {this.onClose.bind(this)}
                    onClose = {this.onClose.bind(this)} 
					title = {creatingTitle}
					footer = {footer}
					>
					<Row justify="center">
						<h3>{creatingMsg}</h3>
					</Row>
            </Dialog>
		<Row style={{padding:"0"}}>
				<Col span="12">
					<Pagination current={this.state.currentPage} total={total} pageSize={this.state.pageSize} pageSizeList={[1,10,20]} pageSizeSelector="dropdown" type="simple" onChange={this.handlePageChange.bind(this)} onPageSizeChange={this.handlePageSizeChange.bind(this)} />
					{/*
						<RadioGroup defaultValue="onseal" onChange={this.handleCheckStatus.bind(this)}>
							<Radio id="all" value="all">全部</Radio>
							<Radio id="runing" value="runing">进行中</Radio>
							<Radio id="waitting" value="waitting">未开始</Radio>
							<Radio id="stoped" value="stoped">已结束</Radio>
						</RadioGroup>
					*/}
				</Col>
				<Col span="12" style={{textAlign:"right"}}>
					<Link to={"/ring_tags_step3?activity_id="+this.state.activity_id+"&act_type="+this.state.act_type+"&is_edit=1"}><Button shape="ghost">添加商品</Button></Link>
					&nbsp;
					<Link to={"/ring_tags"}><Button type="primary">返回列表</Button></Link>
				</Col>
		</Row>
		{noneMsg}
		{doneItems.map((item)=>{
			const menu = <Menu>
							<Menu.Item key={item.detail_id} onClick={this.removeItemInActive.bind(this)}>删除</Menu.Item>
						</Menu>
			const decreaseAmount = (item.ztype=="decreaseAmount")?item.value:"";
			const discountRate = (item.ztype=="discountRate")?item.value:"";					
			const limitCount = parseInt(item.limit_buy_count);
			const limitBuy = this.state.act_type=="limit"?
										<Input 
											style={{width:"120px"}}
											size="large" 
											addonBefore="限"
											value={limitCount}
											onChange={this.changeLimit.bind(this,item)}
											addonAfter="件" 
										/>
										:"";
										
			const decrease = 			<Input 
											style={{width:"120px"}}
											size="large" 
											addonBefore="减"
											state={(item.ztype=="decreaseAmount")?"success":""}
											onChange={this.changePrice.bind(this,"decreaseAmount",item)}
											value={decreaseAmount}
											addonAfter="元" 
										/>;
			const discount = 			<Input 
											style={{width:"120px"}}
											size="large" 
											addonBefore="打" 
											state={item.ztype=="discountRate"?"success":""}
											onChange={this.changePrice.bind(this,"discountRate",item)}
											value={discountRate}
											addonAfter="折" 
										/>;
			return(
				<Row key={item.num_iid} align="center" style={{padding:0,margin:"5px 0",borderBottom:"1px dashed #CCCCCC"}}>
					<Col fixedSpan="5">
						<a href={"https://item.taobao.com/item.htm?id="+item.num_iid} target="_blank"><img style={{border:"1px solid #C7C7C7"}} src={item.pic_url+"_80x80q90.jpg_.webp"} /></a>
					</Col>
					<Col span="4">
						<span><a href={"https://item.taobao.com/item.htm?id="+item.num_iid} target="_blank">{item.title}</a></span>
					</Col>
					<Col>
						<div className="price_number" style={{fontWeight:"bold",width:"70px",float:"left",textAlign:"right",lineHeight:"32px"}}>{item.price}</div>&nbsp;
						{discount}&nbsp;
						{decrease}&nbsp;
						{limitBuy}&nbsp;
						<Input 
							style={{width:"70px"}}
							size="large" 
							placeholder="折后价"
							onChange={this.changePrice.bind(this,"finalPrice",item)}
							value={item.finaPrice}
						/>
					</Col>
					<Col fixedSpan="5">
						<Button.Split menu={menu} size="small" type="secondary" onClick={this.editItemInActive.bind(this,item.num_iid)}>修改折扣</Button.Split>
					</Col>
				</Row>
			)
		})}
        </div>
    );
  }
}


export default connect((state)=> {
  return {
    ring_zhekou_edit_items: state.ring_zhekou_edit_items,
    ring_tags_step3: state.ring_tags_step3
  };
})(RingZhekouEditItems);
